
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Text;
using System.Web.Services.Protocols;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;



namespace Swaf.Messaging
{
	/// <summary>
	/// Summary description for SOAPMessageResolver.
	/// </summary>
	public class SOAPMessageResolver : BaseMessageResolver
	{
		public SOAPMessageResolver()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		#region IMessageResolver Members
		
		public override string format(string baseMessage, Swaf.Container.INameAddressSupport info)
		{
            string result = base.format(baseMessage, info);

			return formatAsSoap(result);
		}
		
		private string formatAsSoap(string inputString)
		{
			string formattedResult = "";
			try
			{
				MemoryStream streamOfData = new MemoryStream();
				SoapFormatter soapFormatter = new SoapFormatter();
				soapFormatter.Serialize(streamOfData, inputString);

				// Set the position to the beginning of the stream.
				streamOfData.Seek(0, SeekOrigin.Begin);

				// Read the first 20 bytes from the stream.
				byte[] byteArray = new byte[streamOfData.Length];
				int count = streamOfData.Read(byteArray, 0, 20);

				// Read the remaining bytes, byte by byte.
				while(count < streamOfData.Length)
				{
					byteArray[count++] = 
						Convert.ToByte(streamOfData.ReadByte());
				}
				char[] charArray = new char[streamOfData.Length];
				for(int i=0; i<streamOfData.Length; i++)
				{
					charArray[i] = (char) byteArray[i];
				}
				formattedResult = new string(charArray);

			}
			catch(Exception e)
			{
				throw e;
				//TAC throw a new exception
			}
			return formattedResult;
		}
		
		#endregion

	}
}
